//
//  GameScene.swift
//  FirstGame
//
//  Created by Apple on 2017/12/21.
//  Copyright © 2017年 Apple. All rights reserved.
//

import SpriteKit
import GameplayKit

class GameScene: SKScene {

    // Footer相关
    var footer: SKNode?
    var btnHome: SKSpriteNode?
    var btnSound: SKSpriteNode?
    var btnPrevious: SKSpriteNode?
    var btnNext: SKSpriteNode?
    
    // 声音相关
    private let kSoundOffKey = "pref_sound"
    var backgroundMusic: SKAudioNode?
    var textAudio: SKAudioNode?
    var soundOff = false {
        didSet {
            // 更换btnSound的图
            let imgName = soundOff ? "button_sound_off" : "button_sound_on"
            btnSound?.texture = SKTexture(imageNamed: imgName)
            
            // 开关backgroundMusic
            let action = soundOff ? SKAction.pause() : SKAction.play()
            backgroundMusic?.run(action)
            backgroundMusic?.autoplayLooped = !soundOff
            
            // 保存声音状态到本地
            UserDefaults.standard.set(soundOff, forKey: kSoundOffKey)
            UserDefaults.standard.synchronize()
        }
    }
    
    
    override func sceneDidLoad() {
        // Footer相关
        footer = childNode(withName: "footer")
        btnHome = childNode(withName: "//buttonHome") as? SKSpriteNode
        btnSound = childNode(withName: "//buttonSound") as? SKSpriteNode
        btnPrevious = childNode(withName: "//buttonPrevious") as? SKSpriteNode
        btnNext = childNode(withName: "//buttonNext") as? SKSpriteNode
        
        // 声音相关
        backgroundMusic = childNode(withName: "backgroundMusic") as? SKAudioNode
        textAudio = childNode(withName: "textAudio") as? SKAudioNode
        soundOff = UserDefaults.standard.bool(forKey: kSoundOffKey)
    }
    
    // SpriteKit 在加载完场景后会调用 didMove(to:) 方法
    override func didMove(to view: SKView) {
        // 延迟播放textAudio
        if let textAudio = textAudio {
            let wait = SKAction.wait(forDuration: 0.2)
            let play = SKAction.play()
            textAudio.run(SKAction.sequence([wait, play]))
        }
    }
    
    /// 获取上一个场景
    ///
    /// - Returns: 上一个场景
    public func getPreviousScene() -> SKScene? { return nil }
    
    /// 获取下一个场景
    ///
    /// - Parameter view: 下一个场景
    public func getNextScene() -> SKScene? { return nil }
    
    func touchDown(at point: CGPoint) {}
    func touchMoved(to point: CGPoint) {}
    func touchUp(at point: CGPoint) {}
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        guard let touch = touches.first else { return }
        let location = touch.location(in: self)
        
        if let footer = self.footer, footer.contains(location) {
            
            let locationInFooter = touch.location(in: footer)
            
            if let btn = self.btnHome, btn.isHidden == false, btn.contains(locationInFooter) {
                goToHomeScene()
            } else if let btn = self.btnSound, btn.isHidden == false, btn.contains(locationInFooter) {
                soundOff = !soundOff    // 切换声音状态
            } else if let btn = self.btnPrevious, btn.isHidden == false, btn.contains(locationInFooter) {
                goToPreviousScene()
            } else if let btn = self.btnNext, btn.isHidden == false, btn.contains(locationInFooter) {
                goToNextScene()
            }
        } else {
            touchDown(at: location)
        }
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for t in touches { touchMoved(to: t.location(in: self)) }
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        for t in touches { touchUp(at: t.location(in: self)) }
    }
    
    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        for t in touches { touchUp(at: t.location(in: self)) }
    }
    
    
    override func update(_ currentTime: TimeInterval) {
        // Called before each frame is rendered
    }
}

extension GameScene {
    func goToHomeScene() {
        print("Home")
        if let scene = SKScene(fileNamed: "HomeScene") {
            goToScene(scene, transition: SKTransition.fade(with: .darkGray, duration: 0.75))
        } else {
            print("未找到HomeScene")
        }
    }
    func goToPreviousScene() {
        print("previous")
        if let scene = getPreviousScene() {
            goToScene(scene, transition: SKTransition.doorsCloseVertical(withDuration: 0.75))
        } else {
            print("无法向上-_-!!")
        }
    }
    func goToNextScene() {
        print("next")
        if let scene = getNextScene() {
            goToScene(scene, transition: SKTransition.doorsOpenVertical(withDuration: 0.75))
        } else {
            print("无法向下-_-!!")
        }
    }
    
    func goToScene(_ scene: SKScene, transition: SKTransition) {
        scene.scaleMode = .aspectFill
        view?.presentScene(scene, transition: transition)
    }
}
